package com.learning.jquizenglish.common.controller;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AudioStreamingController implements
		OnBufferingUpdateListener, OnCompletionListener {

	private String streamingUrl;
	private MediaPlayer mediaPlayer;
	private OnAudioStreamListener mListener;
	
	public AudioStreamingController(){
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
	}
	
	public void setAudioStreamListener(OnAudioStreamListener listener){
		mListener = listener;
	}
	
	public void initDataSource(String url){
		if(mListener!=null){
			mListener.onInitialData();
		}
		streamingUrl = url;
		try {
			mediaPlayer.reset();
			mediaPlayer.setDataSource(streamingUrl); // setup streaming audio
			mediaPlayer.prepare(); // you must call this method after setup the
									// datasource in setDataSource method. After
									// calling prepare() the instance of
									// MediaPlayer starts load data from URL to
									// internal buffer.
			mediaPlayer.setOnBufferingUpdateListener(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public MediaPlayer getMediaPlayer(){
		return mediaPlayer;
	}

	@Override
	public void onCompletion(MediaPlayer arg0) {
	}

	@Override
	public void onBufferingUpdate(MediaPlayer arg0, int percent) {
		Log.d("loading..", percent+" %");
		if (percent == 100) {
			if(mListener!=null){
				mListener.onBufferingUpdateFinish();
			}
			mediaPlayer.setOnBufferingUpdateListener(null);
		}
	}
	
	public void reset(){
		mediaPlayer.reset();
	}
	
	public void onDestroy(){
		mediaPlayer.reset();
		mediaPlayer.release();
	}
	
	public interface OnAudioStreamListener{
		public void onInitialData();
		public void onBufferingUpdateFinish();
	}

}
